package week_04;

public class SearchRange_34 {
    public int[] searchRange(int[] nums, int target) {
        int n = nums.length;
        int[] ans = new int[2];
        // 求第一个>=target的index值
        int left = 0;
        int right = n;
        while (left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] >= target) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        ans[0] = right;
        //求第一个<=target的index值
        left = -1;
        right = n - 1;
        while (left < right) {
            int mid = (right + left + 1) / 2;
            if (nums[mid] <= target) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        ans[1] = right;
        //组合答案
        if (ans[0] > ans[1]) {
            return new int[]{-1, -1};
        } else return ans;

    }
}
